package com.situ.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.mall.constant.RedisConstant;
import com.situ.mall.mapper.ProductMapper;
import com.situ.mall.pojo.Product;
import com.situ.mall.pojo.query.ProductQuery;
import com.situ.mall.pojo.vo.ProductVO;
import com.situ.mall.service.IProductService;
import com.situ.mall.util.LayUITableResult;
import com.situ.mall.util.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class ProductServiceImpl implements IProductService {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ProductMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public LayUITableResult selectByPage(ProductQuery productQuery) {
        PageHelper.startPage(productQuery.getPage(), productQuery.getLimit());
        List<Product> list = productMapper.selectAll(productQuery);
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();
        return LayUITableResult.ok((int) total, list);
    }

    @Override
    public boolean deleteAll(Integer[] ids) {
        int count = productMapper.deleteAll(ids);
        return count > 0;
    }

    @Override
    public boolean deleteById(Integer id) {
        return productMapper.deleteByPrimaryKey(id) == 1;
    }

    @Override
    public boolean insert(Product product) {
        int count = productMapper.insertSelective(product);

        // 将上传的图片保存到redis
        String mainImage = product.getMainImage();
        String imageName = mainImage.substring(QiniuUtils.URL.length());
        redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE_TO_DB, imageName);
        return count == 1;
    }

    @Override
    public boolean updateStatus(Product product) {
        return productMapper.updateByPrimaryKeySelective(product) > 0;
    }

    @Override
    public ProductVO selectById(Integer id) {
        return productMapper.selectVOByPrimaryKey(id);
    }

    @Override
    public boolean update(Product product) {
        return productMapper.updateByPrimaryKeySelective(product) > 0;
    }
}
